package com.keya.base.aop;

import com.keya.base.exception.BusinessException;
import com.keya.base.output.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Slf4j
class GlobalDefaultExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultData defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            log.error("请求异常", e);
            return ResultData.fail(2, businessException.getMessage());
        }
        if (e != null) {
            log.error("请求异常", e);
            return ResultData.fail(2, e.getMessage());
        }

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;
        log.error("请求异常", e);
        return ResultData.fail(2, e.getMessage());
    }
}
